<?php

namespace App\Http\Controllers\Api;

use App\Enums\OrderPay;
use App\Enums\PayMethod;
use App\Exceptions\InvalidRequestException;
use App\Http\Controllers\Controller;
use App\Http\Requests\OrderRequest;
use App\Http\Resources\OrderResource;
use App\Models\Order;
use App\Services\OrderService;
use App\Services\PayService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class OrderController extends Controller
{


    //购买记录
    public function index(Request $request)
    {
        $order = Order::query()->where('user_id', $request->user()->id)
            ->orderByDesc('id')
            ->paginate($request->get('limit', 10));
        return successReturn([
            'list' => OrderResource::collection($order),
            'total' => $order->total(),
            'last_page' => $order->lastPage()
        ]);
    }


    /**
     * 购买
     * @param OrderRequest $request
     * @return JsonResponse
     */
    public function store(OrderRequest $request)
    {
        $order = app(OrderService::class)->buy($request->get('id'), $request->user(), $request->get('pay_method'));
        return successReturn([
            'id' => $order->id,
            'order_no' => $order->order_no,
            'money' => $order->money,
            'title' => $order->project->title,
            'pay_method' => $order->pay_method,
            'pay_expired_time' => $order->pay_expired_time->toDateTimeString(),
            'pay_address' => $order->pay_address,//支付地址
        ]);
    }


    /**
     * 支付
     * @param Request $request
     * @return JsonResponse
     */
    public function pay(Request $request)
    {
        $order = Order::query()->where('id', $request->get('id', 0))
            ->where('user_id', $request->user()->id)
            ->where('pay', OrderPay::WAIT)
            ->first();
        if (!$order) {
            return failReturn('订单状态不允许支付');
        }
        if (now()->gte(Carbon::parse($order->pay_expired_time))) {
            return failReturn('订单已过期');
        }

        return successReturn([
            'id' => $order->id,
            'order_no' => $order->order_no,
            'money' => $order->money,
            'title' => $order->project->title,
            'pay_method' => $order->pay_method,
            'pay_expired_time' => $order->pay_expired_time,
            'pay_address' =>  $order->pay_address,//支付地址
        ]);
    }
}
